package com.superhelper.app.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.superhelper.app.controller.base.AbstractController;
import com.superhelper.app.domain.Resp;
import com.superhelper.app.domain.RespOrder;
import com.superhelper.app.service.DeliverService;
import com.superhelper.app.service.ElemeService;
import com.superhelper.app.service.MtService;
import com.superhelper.app.service.OrderService;
import com.superhelper.app.service.ShopService;
import com.superhelper.app.service.deliver.IDeliverService;
import com.superhelper.common.Consts;
import com.superhelper.common.domain.AuserShop;
import com.superhelper.common.domain.PushMsgType;
import com.superhelper.common.domain.TakeOutOrderStatus;
import com.superhelper.common.domain.WifiAccount;
import com.superhelper.common.service.FeiEService;
import com.superhelper.common.utils.JsonHelper;

import eleme.openapi.sdk.api.exception.ServiceException;

@Controller
@RequestMapping("v1/order")
public class OrderController extends AbstractController {

    @Autowired
    private ShopService shopService;
    @Autowired
    private OrderService orderService;

    @Autowired
    private ElemeService elemeService;

    @Autowired
    private MtService mtService;

    @Autowired
    private IDeliverService dadaService;

    @Autowired
    private FeiEService feiEService;

    @Autowired
    private DeliverService deliverService;

    /**
     * 订单列表
     * 
     * @return
     * @throws ServiceException
     */
    @RequestMapping("list")
    @ResponseBody
    public Resp list(@RequestParam Long userId, String target, @RequestParam Long timestamp,
            @RequestParam Integer pageSize, String phone, HttpServletRequest request) throws ServiceException {

        return orderService.getTakeOutOrder(userId, timestamp, pageSize, target, phone);
    }

    /**
     * 订单处理
     * 
     * @return
     * @throws ServiceException
     */
    @RequestMapping("handle")
    @ResponseBody
    public Resp handle(@RequestParam Long orderId, @RequestParam String opt) throws Exception {

        RespOrder order = orderService.getOrderByOrderId(orderId);
        if (order == null) {
            return fail("订单不存在");
        }
        boolean res = false;
        switch (opt) {
        case "confirm": // 确认订单
            if (order.getStatus().equals(TakeOutOrderStatus.UNPROCESSED.getValue())) {
                res = orderService.confirm(order);
            }
            break;

        case "canel": // 取消订单
            if (order.getStatus().equals(TakeOutOrderStatus.UNPROCESSED.getValue())
                    || order.getStatus().equals(TakeOutOrderStatus.VALID.getValue())) {
                res = orderService.canelOrder(order);
            }
            break;
        case "send": // 发送物流
            res = dadaService.addTask(orderId);
            break;

        case "print": // 打印

            break;

        case "agree": // 同意退款申请
            if (order.getStatus().equals(TakeOutOrderStatus.REFUNDING.getValue())
                    || order.getStatus().equals(TakeOutOrderStatus.APPLY_CANCEL.getValue())) {
                res = orderService.agreeRefund(order);
            } else if (order.getStatus().equals(TakeOutOrderStatus.INVALID.getValue())) {
                res = true;
            }
            break;
        case "disagree": // 退款申请取消
            if (order.getStatus().equals(TakeOutOrderStatus.REFUNDING.getValue())
                    || order.getStatus().equals(TakeOutOrderStatus.APPLY_CANCEL.getValue())) {
                res = orderService.disagreeRefund(order);
            } else {
                res = true;
            }
            break;
        default:
            break;
        }
        log.info("handle：{}-{}-{}-order:{}", orderId, opt, res, JsonHelper.toJson(order));
        return res ? success("操作成功") : fail("操作失败");
    }

    /**
     * 队列信息（pc）
     *
     * @return
     */
    @RequestMapping("mq")
    @ResponseBody
    public Resp redisMq(@RequestParam Long userId) {
        return orderService.queryMsg(userId);
    }

    /**
     * 自动打单(轮询补偿)
     * 
     * @return
     * @throws ServiceException
     */
    @RequestMapping("queryNotPrint")
    @ResponseBody
    public Resp queryOrder(@RequestParam Long userId) {
        List<RespOrder> orders = orderService.querOrderToPrint(userId);
        log.info("queryOrder:{}", JsonHelper.toJson(orders));
        return success(orders);
    }

    /**
     * 更新打单状态
     * 
     * @return
     * @throws ServiceException
     */
    @RequestMapping("print/finish")
    @ResponseBody
    public Resp printFinish(@RequestParam Long userId, @RequestParam String orderIds) {
        int res = orderService.updateProcess(orderIds, 2);
        log.info("updateProcess-{}-{}-{}", orderIds, 2, res);
        return res > 0 ? success("操作成功") : fail("操作失败");
    }

    /**
     * 查询要处理的订单(轮询补偿)
     * 
     * @return
     * @throws ServiceException
     */
    @RequestMapping("query/deal")
    @ResponseBody
    public Resp queryNeedDeal(@RequestParam Long userId) {
        if (isExpireAt(userId)) {
            return resp(com.superhelper.app.common.Consts.Code.USER_EXPIRE);
        }
        Map<String, Object> result = new HashMap<String, Object>();
        List<RespOrder> orders = orderService.queryNeedDeal(userId);
        result.put("orders", orders);
        log.info("queryNeedDeal:{}", JsonHelper.toJson(result));
        return success(result);
    }

    /**
     * 评价列表
     * 
     * @return
     * @throws ServiceException
     */
    @RequestMapping("queryReview")
    @ResponseBody
    public Resp queryReview(@RequestParam Long shopId, HttpServletRequest request) throws Exception {
        mtService.queryReview(shopId + "");
        return success();
    }

    /**
     * 修改送达时间
     * 
     * @return
     * @throws ServiceException
     */
    @RequestMapping("deliverTime")
    @ResponseBody
    public Resp deliverTime(@RequestParam Long orderId, @RequestParam String time) throws Exception {
        int res = orderService.updateDeliverTime(orderId, time);
        return res > 0 ? success() : fail();
    }

    @PostConstruct
    public void initWifiMsg() {
        for (int i = 0; i < 2; i++) { // 启动线程
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    while (true) {
                        String key = Consts.Redis.WIFI_ORDER;
                        String msg = redisService.receive(key, 60);
                        if (StringUtils.isNotBlank(msg)) {
                            try {
                                log.info("{},msg:{}", key, msg);
                                Map map = JsonHelper.fromJson(msg, Map.class);
                                String type = String.valueOf(map.get("type"));
                                String orderId = String.valueOf(map.get("orderId"));
                                RespOrder order = orderService.getOrderByOrderId(Long.parseLong(orderId));
                                AuserShop shop = shopService.getAuserShop(order.getShopId(), order.getType());
                                if (shop.getOrderAuto() == 3) { // wifi接单与打印
                                    if (PushMsgType.ORDER_CREATED.getValue().equals(type)) {// 新订单，进行接单
                                        orderService.confirm(order);
                                    } else if (PushMsgType.ORDER_ACCEPTED.getValue().equals(type)) {// 自动接单，进行打印
                                        WifiAccount wifi = deliverService.getUseWifiAccount(Long.valueOf(shop
                                                .getAuserId()));
                                        if (wifi != null) {
                                            String content = orderService.getContentToPrint(order);
                                            String wifi_orderId = feiEService.sendToPrint(wifi.getSn(), content);
                                            orderService.updateWifiProcess(order.getId(), wifi_orderId, 1);
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                log.error("error:{}", e);
                            }
                        }
                    }
                }
            }).start();
        }

    }
}
